# -*- coding: utf-8 -*-

from genericpath import getsize
import os
import datetime
import zipfile


def file_open():
    """
    打开文件模式
    r 读(read)模式：如果文件不存在，就会报错（打开文件失败）（默认模式）
    w 写(write)模式：如果文件不存在，就创建文件；如果文件存在，就清空文件。
    a 追加(append)模式：如果文件不存在，就创建文件
    b 二进制模式（可添加到其他模式）
    + 读/写模式（可添加到其他模式）
    """

    file = open('file.txt', 'r+')  # 打开文件
    # 刚打开的文件指针在文件开头
    print(file.read())  # 全读（文件指针移到文件末尾）
    print(file.read(10))  # 按字节（字符）数读（文件指针移到相应位置）
    print(file.read())  # 从文件指针当前位置开始全读

    file.seek(0)  # 设置文件指针位置（0为文件开头）
    print(file.read())

    file.write('Hello chench')  # 将内容写到文件缓存区
    file.flush()  # 用来刷新缓冲区的，即将缓冲区中的数据立刻写入文件，同时清空缓冲区。
    # 比较是否注释上一行的效果的差异
    print(file.read())

    if file.closed:  # 检测文件是否关闭
        file.close()  # 关闭文件
        pass
    pass


def write_lines(path, line):
    """以追加模式按行将文本写入文件"""
    with open(path, mode='a+') as file:
        file.write(line + '\n')
        pass
    pass


def create_folder(path):
    """判断文件路径或文件夹是否存在，不存在就创建"""
    if not os.path.exists(path):
        # 从右开始检索路径分隔符
        # index = path.rfind(os.sep)
        # if index == -1:
        #     folder = path
        # else:
        #     folder = path[:index]
        #     pass

        # 使用os.path模块
        folder = os.path.dirname(path)
        if not os.path.exists(folder):
            os.makedirs(folder)
            pass
        pass
    pass


def file_system():
    files = os.listdir('../py_os')
    for file in files:
        print(file)

        pass

    pass


def get_folder_size(folder):
    # 获取文件大小
    # size = os.path.getsize('json.json')

    # 记录文件夹的大小
    size = 0
    for abs_path, folders, files in os.walk(folder):
        # 递归调用统计子文件夹的大小
        size += sum([get_folder_size(folder_path) for folder_path in folders])
        # 统计文件的大小
        size += sum([os.path.getsize(os.path.join(abs_path, file_name)) for file_name in files])
        pass
    return size


def compress_folder(zip_path, folder):
    """文件夹压缩"""
    with zipfile.ZipFile(zip_path, 'a') as zip_file:
        for abs_path, folders, files in os.walk(folder):
            for file_name in files:
                file_path = os.path.join(abs_path, file_name)
                zip_file.write(file_path, file_name)
                pass
            pass
        pass
    pass


def compress_file(zip_path, file_path, arc_name):
    """压缩文件"""
    with zipfile.ZipFile(zip_path, 'a') as zip_file:
        zip_file.write(file_path, arc_name)
        pass
    pass


def extract_zip(file, path):
    """从压缩包提取文件"""
    with zipfile.ZipFile(file, 'r') as zip_file:
        zip_file.extractall(path)
        pass
    pass


if __name__ == '__main__':
    # file_path = './logs/1/1/file.log'
    # create_folder(file_path)

    # file_system()

    # print(get_folder_size('..'))

    # file_open()

    # compress_folder('zip.zip', '../py_os')
    zip_path = '/Users/hn/Desktop/zip.zip'
    compress_file('/Users/hn/Desktop/zip.zip', 'py_path.py', 'py_io/py_path.py')
    extract_zip(zip_path, '/Users/hn/Desktop/zip')

    pass
